<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- 索赔结算单查询-详情页面 -->
      <BreakSpace label="结算单信息" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <BreakSpace label="索赔单列表" :containerStyle="{ marginBottom: '10px' }" />

      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :datakey="'items'"
        :onColumnsChange="(columns) => (this.columns = columns)"
        :onRowSelectChange="selectChange"
        :isPagination = false
        :isSelectColumn="false"
        height="auto"
        :is-select-column= false
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="text" style="font-size: 14px; color: #bb2801; font-weight: bold">
            <span v-text="`每个结算单只可维护同类车辆属性的索赔单`"></span>
          </el-button>
<!--          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="suopeidanadd()">添加</multiuse-button>-->
        </template>
      </FilterTable>
      <BaseDialog :visible.sync="suopeidanFlag" :title="'索赔单选择'" destroyOnClose width="850px" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <Selectsuopeidan @close="suopeidanclose" @save="suopeidansave" :rowData="rowData"></Selectsuopeidan>
      </BaseDialog>
      <BreakSpace label="考核单列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="table1"
        :columns="columns1"
        :params="fetchParams"
        :datakey="'items'"
        :onColumnsChange="(columns1) => (this.columns1 = columns1)"
        :onRowSelectChange="selectChange"
        :isPagination = false
        :isSelectColumn="false"
        height="auto"
        :is-select-column="false"
      >
        <template slot="controls" slot-scope="props">
          <el-button size="small" type="text" style="font-size: 14px; color: #bb2801; font-weight: bold">
            <span v-text="`每个结算单只可维护同类车辆属性的考核单`"></span>
          </el-button>
<!--          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="kaohedanadd()">添加</multiuse-button>-->
        </template>
      </FilterTable>
      <div style="margin-bottom: 1rem;"></div>
      <BaseDialog :visible.sync="kaohedanFlag" :title="'考核单选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <SelectKaoHedan @close="kaohedanclose" @save="kaohedansave" :rowData="rowData"></SelectKaoHedan>
      </BaseDialog>
      <div style="padding-top: 3rem"></div>
      <div
        :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
      >
        <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
import Selectsuopeidan from './Selectsuopeidan.vue';
import SelectKaoHedan from './SelectKaoHedan.vue';
import {  getPartType, getclaimType, deleteOne, newSave } from '@/api/claim/dealer/ClaimStatementMaintain';
import {  getAppId } from '@/assets/js/auth';
import { getListByPage,downloadModel,getListForExport } from '@/api/claim/dealer/CheckSheetQueryDealer';
import { getSpList } from '@/api/claim/dealer/ClaimQueryDealer/index';
import { dictionary } from '@/utils/dictMixin';
// import { BasicParametersAfterSales } from '@/api/dictionary/index';
export default {
  mixins: [dictionary],
  components: {
    Selectsuopeidan,
    SelectKaoHedan,
  },
  data() {
    return {
      loading: false,
      rowData: {},
      dataList: [],
      dataList1: [],
      arry: [],
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      visible: false,
      //索赔单列表开关
      suopeidanFlag: false,
      kaohedanFlag: false,
      visibleDrawer: false,
      kaohesum: 0,
      suopeisum: 0,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columns1: this.creatHeader1(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
    };
  },
  async created() {
    this.loading = true;
    if (getAppId() == 'arcfox') {
      this.formList.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543',[55431001])
    }else{
      this.formList.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543')
    }
    await this.chuqi();
    this.loading = false;
  },
  methods: {
    deleteFunkaohe(costItem) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.$notify({
            title: '提示信息',
            message: '删除成功',
            type: 'success',
          });
          this.$refs.table1.$refs.pageTable.EXECUTE_DELETE([costItem]);

          this.formList.map((x) => {
            if ('assessAmount' == x.fieldName) {
              x.initialValue = this.kaohesum - Number(costItem.assessAmount);
              this.kaohesum = this.kaohesum - Number(costItem.assessAmount);
              this.sumAmount();
            }
          });
        })
    },
    deleteFunsuopei(costItem) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.$notify({
            title: '提示信息',
            message: '删除成功',
            type: 'success',
          });
          this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);
          // let list = [...this.$refs.table.$refs.pageTable.list];
          // this.$refs.table.$refs.pageTable.EXECUTE_DELETE(list);
          // this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
          this.formList.map((x) => {
            if ('claimAmount' == x.fieldName) {
              x.initialValue = Number(this.suopeisum - Number(costItem.finalSumAmount)).toFixed(2);
              this.suopeisum = Number(this.suopeisum - Number(costItem.finalSumAmount)).toFixed(2);
              this.sumAmount();
            }
          });
          // let arry = this.$refs.table.$refs.pageTable.list;
          // this.$refs.table.$refs.pageTable.EXECUTE_DELETE(arry);
          // this.$refs.table.$refs.pageTable.list.map((x) => {
          //   delete x.index;
          // });
          // this.$refs.table.$refs.pageTable.EXECUTE_INSERT(arry);
          if(!this.$refs.table.$refs.pageTable.list.length){
            this.formList.find((x) => x.fieldName === 'carType').disabled = false;
          }
        })
    },

    sumAmount() {
      let sum = 0;

      //索赔金额
      this.$refs.table.$refs.pageTable.list.map((x) => {
        sum += Number(x.finalSumAmount);
      });
      //考核金额
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        sum += Number(x.assessAmount);
      });

      // this.$refs.peijianhuanshangjiantable.$refs.pageTable.list.map(x => {
      //   sum += Number(x.cmsClaimPrice);
      // });

      this.formList.map((x) => {
        if ('settleAmount' == x.fieldName) {
          x.initialValue = parseFloat(sum).toFixed(2);
        }
      });
    },
    //索赔车辆属性
    async chuqi() {
      // let res = await BasicParametersAfterSales();
      // this.invoiceMax = res.data[2001];
      // const res = await getPartType({ type: 5543 });
      // if(getAppId()=='arcfox'){
      //   delete res.data[0]
      //   this.formList.find((x) => x.fieldName == 'carType').initialValue = 55431002;
      // }
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'carType').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }

      // //单据状态
      // const res1 = await getPartType({ type: 5546 });
      // if (res1.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'settleStatus').initialValue = 55461001;
      //   this.formList.find((x) => x.fieldName == 'settleStatus').itemList = res1.data.map((y) => ({
      //     text: y.codeCnDesc,
      //     value: y.codeId,
      //   }));
      // }



    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
    },
    //索赔单计算
    async suopeidansave(val) {
      // let list = this.$refs.table.$refs.pageTable.list;
      // let values = [];
      // val.map(v => {
      //   if(!list.find(x => x.claimId == v.claimId)){
      //     values.push(v);
      //   }
      // });
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      this.loading = true;
      const res = await getSpList({ifComm: val,claimStatus : 55131003 ,status:3,pageNum:1,currentPage:1,pageSize:99999999,limit:99999999,qualifyStatus:55061001})
      this.loading = false;
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(res.data.records);
      let suopeijine = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        if(x.ifPrice == '是'){
          x.finalSumAmount =x.priceAmount;
        }
        suopeijine += Number(x.finalSumAmount);
      });
      this.formList.map((x) => {
        if ('claimAmount' == x.fieldName) {
          x.initialValue = Number(suopeijine).toFixed(2);
        }
      });
      this.suopeisum = suopeijine;
      this.sumAmount();
      // this.formList.find((x) => x.fieldName === 'carType').disabled = true;
      this.suopeidanFlag = false;
      // this.fetchParams = { ...this.fetchParams };
    }, //考核单计算
    async kaohedansave(val) {
      this.$refs.table1.$refs.pageTable.EXECUTE_DELETE(this.$refs.table1.$refs.pageTable.list);
      this.loading = true;
      const res = await getListByPage({assessClassify: val, assessStatus:55451004,statusForFlag:3,pageNum:1,currentPage:1,pageSize:99999999,limit:99999999})
      this.loading = false;
      // let list = this.$refs.table1.$refs.pageTable.list;
      // let values = [];
      // val.map(v => {
      //   if(!list.find(x => x.assessId == v.assessId)){
      //     values.push(v);
      //   }
      // });
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(res.data.records);

      let kaohejine = 0;
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        kaohejine += Number(x.assessAmount);
      });
      this.formList.map((x) => {
        if ('assessAmount' == x.fieldName) {
          x.initialValue = Number(kaohejine);
        }
      });
      this.kaohesum = kaohejine;
      this.sumAmount();
      this.kaohedanFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    suopeidanclose() {
      this.suopeidanFlag = false;
    },
    suopeidanadd() {
      this.formList.find((x) => x.fieldName === 'carType').rules = [{ required: true, message: '添加索赔单前，请选择车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'carType').initialValue) {
        this.$refs.formPanel.SUBMIT_FORM();
        if(this.$refs.table.$refs.pageTable.list.length && this.$refs.table.$refs.pageTable.list[0].ifComm != this.saveData.carType){
          return this.$notify({
            title: '提示信息',
            message: '当前车辆属性,与索赔车辆属性不一致!',
            type: 'error'
          });
        }
        this.rowData = this.saveData;
        this.suopeidanFlag = true;
      }
    },
    kaohedanclose() {
      this.kaohedanFlag = false;
    },
    kaohedanadd() {
      this.formList.find((x) => x.fieldName === 'carType').rules = [{ required: true, message: '添加考核单前，请选择车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'carType').initialValue) {
        this.$refs.formPanel.SUBMIT_FORM();
        if(this.$refs.table.$refs.pageTable.list.length && this.$refs.table.$refs.pageTable.list[0].ifComm != this.saveData.carType){
          return this.$notify({
            title: '提示信息',
            message: '当前车辆属性,与索赔车辆属性不一致!',
            type: 'error'
          });
        }
        this.rowData = this.saveData;
        this.kaohedanFlag = true;
      }

    },

    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();

      let str = '';
      this.$refs.table.$refs.pageTable.list.map((x) => {
        str += x.claimId + ',';
      });

      let str1 = '';
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        str1 += x.assessId + ',';
      });

      //存储索赔单数
      if (this.saveData !== null) {
        this.saveData.claimIds = str;
        this.saveData.assessIds = str1;
        this.saveData.claimCount = this.$refs.table.$refs.pageTable.list.length;
        this.saveData.labourAmount =  0;
        this.saveData.partAmount = 0;
        this.saveData.addAmount = 0;
        this.$refs.table.$refs.pageTable.list.map(x => {
          this.saveData.labourAmount += Number(x.labourAmount);
          this.saveData.partAmount += Number(x.partAmount);
          this.saveData.addAmount += Number(x.addAmount);
        });
        // if(Number(this.saveData.settleAmount)>Number(this.invoiceMax)){
        //   return this.$notify.error({title: '提示信息', message: '结算金额不得大于发票单张金额['+this.invoiceMax+']！'});
        // }

        if((this.$refs.table.$refs.pageTable.list.length!==0)&&(this.formList.find((x) => x.fieldName === 'carType').initialValue)){
          this.loading = true;
          let res = await newSave(this.saveData);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.loading = false;
            // this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            // this.closeDialog();
          }
          this.loading = false;
        }else{ return this.$notify.error({title: '提示信息', message: '请检查索赔单列表或索赔车辆属性是否添加！'});
          this.loading = false;
        }

      } else {
        return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {},
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'settleNo',
          disabled: true, // 只读
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商代码',
        //   fieldName: 'dealerCode',
        //   disabled: true, // 只读
        // },
        // {
        //   type: 'INPUT',
        //   label: '经销商名称',
        //   fieldName: 'dealerName',
        //   disabled: true, // 只读
        // },
        {
          type: 'INPUT',
          label: '索赔金额',
          fieldName: 'claimAmount',
          disabled: true, // 只读
        },
        {
          type: 'INPUT',
          label: '考核金额',
          fieldName: 'assessAmount',
          disabled: true, // 只读
        },
        {
          type: 'INPUT',
          label: '结算金额',
          fieldName: 'settleAmount',
          disabled: true, // 只读
        },
        {
          type: 'SELECT',
          label: '结算单状态',
          fieldName: 'settleStatus',
          disabled: true, // 只读
          initialValue: 55461001,
          //rules: [{ message: '请选择结算单状态', trigger: 'blur' }],
          itemList: this.createDictList('5546'),
        },
        {
          type: 'INPUT',
          label: '提交时间',
          fieldName: 'applyDate',
          disabled: true, // 只读
        },
        {
          type: 'SELECT',
          label: '索赔车辆属性',
          fieldName: 'carType',
          placeholder: '请选择',
          initialValue: '',
          rules: [],
          itemList: [],
          disabled: false,
          change: val => {

            if(val){
              this.loading = true;
              this.kaohedansave(val)
              this.suopeidansave(val)
              this.loading = false;
            }

          }
        },
      ];
    },
    //索赔单列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button type="text" onClick={() => this.deleteFunsuopei(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        { title: '维修工单号', dataIndex: 'roNo', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        { title: '是否一口价', dataIndex: 'ifPrice', sorter: true },
        { title: '索赔金额', dataIndex: 'finalSumAmount', sorter: true },
        { title: '工时费', dataIndex: 'labourFinalPrice', sorter: true },
        { title: '配件费', dataIndex: 'partrFinalPrice', sorter: true },
        { title: '附加费用', dataIndex: 'addFinalPrice', sorter: true },
        { title: '审核时间', dataIndex: 'checkAt', sorter: true },
        { title: '审核人', dataIndex: 'checkBy', sorter: true },
      ];
    },
    //考核单列表
    creatHeader1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 100,
        //   fixed: 'left',
        //   render: (props) => {
        //     return (
        //       <div style="text-align:center">
        //         <multiuse-button type="text" onClick={() => this.deleteFunkaohe(props.row)} >
        //           删除
        //         </multiuse-button>
        //       </div>
        //     );
        //   },
        // },
        { title: '考核单号', dataIndex: 'assessNo', sorter: true },
        { title: '考核类型', dataIndex: 'assessTypeStr', sorter: true },
        { title: '考核金额', dataIndex: 'assessAmount', sorter: true },
        { title: '考核原因', dataIndex: 'assessReason', sorter: true },
        { title: '考核日期', dataIndex: 'assessDate', sorter: true },
        { title: '考核人', dataIndex: 'assessBy', sorter: true },
      ];
    },
  },
};
</script>
<style lang="less" scoped></style>
